'use client'

import { useEffect, useState } from 'react'
import { VmsCopy } from '@/types/Model'
import { useParams, useRouter } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import TailwindAdvancedEditor from "@/components/tailwind/advanced-editor"

export default function CopyEditPage() {
  const { id } = useParams()
  const router = useRouter()
  const [copy, setCopy] = useState<VmsCopy | null>(null)
  const [loading, setLoading] = useState(true)

  const fetchCopy = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy/${id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        if (response.status === 404) {
          // 文案不存在，清理相关的 localStorage 缓存
          localStorage.removeItem('novel-content')
          localStorage.removeItem('html-content')
          localStorage.removeItem('markdown')
          
          // 检查并清理 lastViewedCopy（仅当匹配当前文案ID时）
          const lastViewed = localStorage.getItem('lastViewedCopy')
          if (lastViewed) {
            try {
              const { copyId } = JSON.parse(lastViewed)
              if (copyId === id) {
                localStorage.removeItem('lastViewedCopy')
              }
            } catch (error) {
              // 如果解析失败，直接清理
              localStorage.removeItem('lastViewedCopy')
            }
          }
          
          toast({
            title: '文案不存在',
            description: '该文案可能已被删除，正在返回项目列表',
            variant: 'destructive'
          })
          
          router.push('/topics')
          return
        }
        
        if (response.status === 401) {
          router.push('/login')
          return
        }
        
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      
      const data = await response.json()
      setCopy(data)
      
      toast({
        title: '数据获取成功',
        description: '文案详情已加载',
      })
    } catch (error) {
      console.error('Error fetching copy:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      
      // 如果是网络错误或其他错误，也重定向到安全页面
      setTimeout(() => {
        router.push('/topics')
      }, 2000)
    } finally {
      setLoading(false)
    }
  }
  const saveCopy = async (copy: VmsCopy) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(copy)
      })
      
      if (!response.ok) {
        throw new Error('Failed to save copy')
      }
      
      toast({
        title: '保存成功',
        description: '文案已成功保存',
      })
      
      // Optionally refresh the data
      await fetchCopy()
    } catch (error) {
      console.error('Error saving copy:', error)
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (id) {
      fetchCopy()
    }
  }, [id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  if (!copy) {
    return <div>未找到文案</div>
  }

  return (
       <div className='flex justify-center w-full py-8'>
         <TailwindAdvancedEditor 
            copy={copy}
            saveCopy={saveCopy}
        />
       </div>
  )
}
